<template>
  <div class="form-group">
    <h4 class="group-title">培训计划</h4>
    <div class="table-wrapper">
      <!-- 表格添加空数据提示 -->
      <el-table
        :data="trainingPlans"
        border
        style="width: 100%;"
        class="custom-table"
        empty-text="暂无培训计划数据"
      >
        <el-table-column label="培训内容" width="200">
          <template #default="scope">
            <!-- 禁用输入框 -->
            <el-input
              v-model="scope.row.content"
              placeholder="请输入培训内容"
              class="custom-input"
              :disabled="true"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 开始时间列 -->
        <el-table-column label="开始时间" width="200">
          <template #default="scope">
            <!-- 禁用日期选择器 -->
            <el-date-picker
              v-model="scope.row.startTime"
              type="date"
              placeholder="选择开始日期"
              class="custom-input"
              :disabled="true"
              @change="handleDateChange(scope.row, 'startTime')"
            ></el-date-picker>
          </template>
        </el-table-column>

        <!-- 结束时间列 -->
        <el-table-column label="结束时间" width="200">
          <template #default="scope">
            <!-- 禁用日期选择器 -->
            <el-date-picker
              v-model="scope.row.endTime"
              type="date"
              placeholder="选择结束日期"
              class="custom-input"
              :disabled="true"
            ></el-date-picker>
          </template>
        </el-table-column>

        <el-table-column label="培训地点" width="150">
          <template #default="scope">
            <!-- 禁用输入框 -->
            <el-input
              v-model="scope.row.location"
              placeholder="请输入培训地点"
              class="custom-input"
              :disabled="true"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column label="培训教师" width="150">
          <template #default="scope">
            <!-- 禁用选择器 -->
            <el-select
              v-model="scope.row.teacher"
              placeholder="请选择教师"
              class="custom-input"
              :disabled="true"
            >
              <el-option
                v-if="memberOptions.length === 0"
                value=""
                disabled
              >
                暂无可用教师数据
              </el-option>
              <el-option
                v-else
                v-for="user in memberOptions"
                :key="user.userId"
                :label="user.nickName || user.userName"
                :value="user.userId"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="说明" >
          <template #default="scope">
            <!-- 禁用输入框 -->
            <el-input
              v-model="scope.row.description"
              placeholder="请输入说明"
              class="custom-input"
              :disabled="true"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { queryNonMemberUsers } from "@/api/system/user"
import { listByClassId, batchUpdateByClass } from "@/api/training/TrainingSchedule";
import dayjs from 'dayjs';

export default {
  name: "TrainingPlanSetting",
  props: {
    classId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      submitLoading: false,
      memberOptions: [],
      trainingPlans: []  // 初始化为空数组，无数据时触发空提示
    };
  },
  created() {

  },
  watch:{
    classId:{
      handler(newVal){
        this.getMembersList();
      }
    }
  },
  methods: {
    getTeacherName(teacherId) {
      if (!teacherId) return '';

      const teacher = this.memberOptions.find(
        user => user.userId === teacherId
      );

      return teacher ? (teacher.nickName || teacher.userName || '未知教师') : '未知教师';
    },

    async getMembersList() {
      try {
        const userRes = await queryNonMemberUsers();
        this.memberOptions = userRes.rows || [];
        this.loadTrainingPlanData();
      } catch (error) {
        console.error("人员数据加载失败：", error);
        this.$message.error("人员信息加载失败，请稍后重试");
        this.memberOptions = [];
      }
    },

    // 日期处理逻辑（仅用于数据加载时的格式转换，不处理用户交互）
    handleDateChange(row, field) {
      if (field === 'startTime' && row.startTime && row.endTime) {
        if (dayjs(row.startTime).isAfter(dayjs(row.endTime))) {
          row.endTime = row.startTime;
        }
      }
    },

    // 处理培训计划数据：无数据时返回空数组（触发表格空提示）
    handlePlansData(backendPlans) {
      if (!Array.isArray(backendPlans) || backendPlans.length === 0) {
        return [];  // 无数据时返回空数组，不再默认添加空行
      }

      return backendPlans.map(plan => {
        // 处理开始时间 - 转换为 Date 对象
        let startTime = null;
        if (plan.scheduleStartTime) {
          const startDate = dayjs(plan.scheduleStartTime);
          if (startDate.isValid()) {
            startTime = startDate.toDate();
          }
        }

        // 处理结束时间 - 转换为 Date 对象
        let endTime = null;
        if (plan.scheduleEndTime) {
          const endDate = dayjs(plan.scheduleEndTime);
          if (endDate.isValid()) {
            endTime = endDate.toDate();
          }
        }

        return {
          content: plan.trainingContent || "",
          startTime: startTime,
          endTime: endTime,
          location: plan.scheduleAddress || "",
          teacher: Number(plan.scheduleTeacherId) || "",
          description: plan.scheduleRemarks || "",
          trainingContentId: plan.trainingContentId || "",
          personnelLimit: plan.personnelLimit || "",
          needReservation: plan.needReservation || ""
        };
      });
    },

    async loadTrainingPlanData() {
      if (!this.classId || this.memberOptions.length === 0) return;

      try {
        this.submitLoading = true;
        const response = await listByClassId(this.classId);

        if (response && response.code === 200) {
          const backendPlans = response.rows || [];
          this.trainingPlans = this.handlePlansData(backendPlans);
        }
      } catch (error) {
        console.error(`加载培训计划数据失败：`, error);
        this.$message.error(`加载培训计划数据失败`);
      } finally {
        this.submitLoading = false;
      }
    },

    // 以下方法保留但实际不会被调用（因为交互入口已移除）
    addTrainingPlanRow() {
      this.trainingPlans.push({
        content: "",
        startTime: null,
        endTime: null,
        location: "",
        teacher: "",
        description: "",
        trainingContentId: "",
        personnelLimit: "",
        needReservation: ""
      });
    },

    deleteTrainingPlanRow(index) {
      if (this.trainingPlans.length > 1) {
        this.trainingPlans.splice(index, 1);
      } else {
        this.$message.warning("至少保留一项培训计划");
      }
    },

    validatePlanData() {
      return true;
    },

    async submitPlanData() {
      return false;
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.form-group {
  margin-bottom: 32px;
}
.group-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 4px solid #165DFF;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  margin: 16px 0;
}

.custom-table {
  border-color: #f0f0f0;
}
.custom-table th {
  background-color: #f5f7fa;
  color: #444;
  font-weight: 500;
  font-size: 14px;
}
.custom-table td {
  color: #666;
  font-size: 14px;
}
.custom-table .el-table__row:hover {
  background-color: #fafbfc;
}
.custom-table .el-table__cell {
  padding: 12px 8px;
}

.custom-input {
  width: 100%;
  height: 36px;
  border-radius: 4px;
}
.custom-input .el-input__inner,
.custom-input .el-select__input {
  padding: 0 12px;
  height: 36px;
}

@media (max-width: 768px) {
  .form-group {
    padding: 0 10px;
  }
}
</style>
